//
//  HHConversationModel.m
//  HHChatKit
//
//  Created by Henry on 2021/5/10.
//

#import "HHConversationModel.h"
#import <HHTool/HHTool.h>
#import "HHChatConfiguration.h"
#import "UIImage+HHChat.h"

@implementation HHConversationModel

- (BOOL)isRead {
    return self.unread <= 0;
}

- (NSString *)badgeValue {
    if (self.isRead) {
        return nil;
    }
    if (self.convType == HHConversationTypePersonal || self.convType == HHConversationTypeGroup) {
        return self.unread <= 99 ? @(self.unread).stringValue : @"99+";
    } else {
        return @"";
    }
}

- (instancetype)initWithType:(HHConversationType)convType {
    if (self = [super init]) {
        _convType = convType;
        [self defaultInit];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self defaultInit];
    }
    return self;
}

- (void)defaultInit {
    _config = [[HHConversationCellConfig alloc] init];
}

- (void)setMembers:(NSArray<HHUserModel *> *)members {
    if (_members == members) {
        return;
    }
    for (HHUserModel *model in members) {
        if (!model.portrait && !model.portraitImage) {
            [model configDefaultImage];
        }
    }
    _members = members;
}

- (NSString *)getConversationTitle {
    if (_name.length > 0) {
        return _name;
    }
    if (_members.count > 0) {
        NSString *title = @"";
        if (_members.count == 1) {
            return _members[0].name;
        }
        for (HHUserModel *model in _members) {
            // 排除自己
            if (![HHChatConfiguration isSelf:model.userId]) {
                
                if (title.length > 0) {
                   title = [title stringByAppendingFormat:@",%@", model.name];
                } else {
                    title = model.name;
                }
            }
            // 最大20
            if (title.length > 20) {
                return title;
            }
        }
        return title;
    }
    return @"未知标题";
}

- (void)resetConversationImage {
    [UIImage hh_getConversationImage:self];
}

@end
